Skip to content

feat(leagues): add weekly leagues with Redis standings and Sunday rollover - #382

Merged
VarshithReddy2006 merged 2 commits into
VarshithReddy2006:mainfrom
Anshuu2004:feat/issue-353-weekly-leagues
Nov 16, 2026
Merged

VarshithReddy2006 merged 2 commits into
VarshithReddy2006:mainfrom
Anshuu2004:feat/issue-353-weekly-leagues

Conversation

@Anshuu2004

Copy link
Copy Markdown
Contributor

Summary

Adds the weekly leagues module from #353: Bronze to Grandmaster divisions, cohorts of about 30, live standings in Redis sorted sets, a score worker fed by XP awards, and a Sunday 00:00 UTC rollover that promotes the top 20%, demotes the bottom 20% and is safe to run more than once for the same week.

What changed

  • backend/src/db/models/leagueStanding.model.ts (new) + leagueStandingIndexes.ts: one row per user per week (weekKey, division, cohortId, status active/finalized, joinedAt, final points/rank/outcome/nextDivision). Unique index on (weekKey, userId). The row is created as active when a user is placed in a cohort and flipped to finalized by the rollover, so it is also where the cohort membership lives (needed to rebuild Redis).
  • backend/src/db/models/userSettings.model.ts: leagues.participate, default false.
  • backend/src/db/migrations/0012-leagues.ts + run-leagues.ts + npm run migrate:leagues: creates the indexes, backfills leagues.participate: false on existing settings, down drops the indexes and the settings field (standing rows are kept). Number 0012 because 0011 is the last one on main, the issue text says 0015.
  • modules/leagues/cohorts.ts: seeded deterministic split into cohorts of 30; a leftover under 10 is merged into the previous cohort; late joiners go into the emptiest cohort under 30, else a new one.
  • modules/leagues/scoreStore.ts: small LeagueScoreStore interface (incrementOnce, seed, replace, remove, ranked, exists, expire) and the ioredis implementation. Increments run as one Lua script (SADD an applied-id, then ZINCRBY), so a replayed award counts once.
  • modules/leagues/leagues.service.ts: join/opt-out, recordXpAward, standings read (ZREVRANGE ... WITHSCORES equivalent, username/avatar from User, rank, points, countdown to the reset), and rebuild of a cohort or a whole week from XpTransaction. A missing Redis set is rebuilt on read and also before a rollover ranks it.
  • modules/leagues/rollover.ts: runWeeklyRollover(weekKey). Phase 1 finalizes each cohort (rank, points, outcome, next division), phase 2 places opted-in users in new cohorts for the next week with $setOnInsert, phase 3 seeds the new Redis boards with ZADD NX and sets a 14 day TTL on the old ones, then sends an SSE league_week_finalized event per finalized user.
  • modules/leagues/workers/leagueScore.worker.ts: BullMQ worker on queue league-score plus enqueueLeagueScore.
  • modules/leagues/workers/weeklyRollover.worker.ts: worker on league-rollover plus scheduleWeeklyRollover (repeatable 0 0 * * 0, tz UTC). The job finalizes the week before the one it runs in, so a late run still finalizes the right week.
  • modules/leagues/leagues.routes.ts, mounted in routes/index.ts: GET /api/v1/leagues/current and PUT /api/v1/leagues/participation ({ participate: boolean }, strict zod).
  • modules/xp/processor.ts: after an award is committed and it is more than 0 XP, enqueue a league score job (failure is logged and ignored, it never fails the XP award).
  • shared/jobs/types.ts: queue names and job data types. workers/worker-runtime.ts: the score worker runs with the xp role, the rollover worker (and its schedule) with the maintenance role. worker-runtime.test.ts updated for the two new workers.
  • SSE: league_week_finalized event type, league.week.finalized domain event type and allowlist entry.
  • README.md: endpoint row and a short migration/ops note.

What I used instead of an xp.awarded event

The xp.awarded type exists in the event contract and the SSE bridge, but nothing on main publishes it (the XP processor only calls the in-process SSE eventBus). So I did not invent a publisher for the whole event system. Instead the XP processor, which is the only place that writes XpTransaction rows, enqueues one league-score job per committed award with { userId, sourceType, sourceId, xpAwarded, occurredAt }. Same data as the xp.awarded payload plus the ledger timestamp. If an xp.awarded publisher lands later, the worker handler (processLeagueScoreJob) can be called from that consumer unchanged.

Anti-gaming: the processor writes no ledger row and returns early for a focus session that does not qualify, and xpAwarded > 0 is required before anything is enqueued, so those add 0. Only the server-written amount is used, nothing comes from the client.

How I tested

Run from backend/, one file at a time, with the repo's src/__tests__/vitest.setup.ts (in-memory MongoDB, ioredis and bullmq mocked), NODE_OPTIONS="--disable-wasm-trap-handler --max-old-space-size=3072":

npx vitest run src/__tests__/modules/leagues/cohorts.test.ts            # 14 passed
npx vitest run src/__tests__/modules/leagues/weeks.test.ts              # 6 passed
npx vitest run src/__tests__/modules/leagues/scoreStore.test.ts         # 8 passed
npx vitest run src/__tests__/modules/leagues/rollover.test.ts           # 38 passed
npx vitest run src/__tests__/modules/leagues/leagues.routes.test.ts     # 7 passed
npx vitest run src/__tests__/modules/leagues/leagues.migration.test.ts  # 2 passed
npx vitest run src/__tests__/modules/leagues/xp-league-hook.test.ts     # 4 passed
npx vitest run src/workers/worker-runtime.test.ts                       # 33 passed
npx vitest run src/__tests__/db/modelIndexes.test.ts                    # 2 passed (needed the new model import)

Existing files I ran to check I did not break anything near my changes, all passing: xp-processor.test.ts (31), xp-concurrency.test.ts (5), consumer-inbox.test.ts (18), ops-cross-process-dlq.test.ts (4), dlq.test.ts (13), settings.persistence.test.ts (11).

npx tsc --noEmit: the same 5 errors as clean main (the unbuilt @devtrack/ats-core import and 3 implicit any in ResumeMLService.ts), none in the files of this PR.

The new module does not exist on main, so every league test fails there by definition. For the one change to existing behaviour I checked it directly: with processor.ts reverted to main, xp-league-hook.test.ts fails on "enqueues the ledger-backed amount once" (the three negative cases pass on main as expected).

What the tests cover (Redis is FakeScoreStore, an in-memory sorted set with ZREVRANGE ordering; no Redis server is used anywhere):

  • cohort assignment: bronze default, last finalized division otherwise, fills to 30 then opens c2, 3 concurrent joins give one row, tail-merge for leftovers under 10, deterministic for a seed
  • score increments: ZINCRBY semantics, first award of the week places an opted-in user, non opted-in user ignored, 0 / negative / fractional XP ignored, a replayed award counts once, XP from before the join or after the week was finalized is dropped, XP lands in the week of its ledger timestamp
  • rollover: ranks and points saved, top 20% up one division, bottom 20% down one, bronze not demoted, grandmaster not promoted, cohorts under 5 move nobody (20% rounded down), next week cohorts and Redis boards created, SSE notification payloads, a failing notification does not fail the rollover
  • idempotency: running it a second and third time changes no row, no Redis score, sends no notification, and a promoted user is exactly one division up. Also: crash after phase 1 is repaired on rerun (new week rebuilt identically, no re-notify), half-finalized cohort ranks the same, opted-out users are not carried over
  • Redis rebuild: flush then rebuildWeekFromLedger, on-demand rebuild on a standings read, and a rollover after a flush ranks from the ledger (only XP of that week and after the user joined counts)
  • routes: 401 without auth, default "not participating", opt in then read standings (rank, username, avatar, points, countdown), opt out, 400 for bad bodies
  • migration: indexes created, backfill does not overwrite an existing true, runs twice, rollback runs twice and on a DB that never migrated
  • the Redis adapter against a stub client (Lua script args, ZREVRANGE parsing, ZADD NX, MULTI replace)

Not tested / notes

  • No real Redis and no real BullMQ run. The Lua script and the repeatable job registration are only checked through stubs / the repo's BullMQ mock, so the first real Redis run is where a mistake there would show up.
  • Full backend suite not run (I ran the files listed above).
  • docs/v2/* (DATABASE_SCHEMA_V2.md section 5.9, BACKEND_SPECIFICATION_V2.md section 13, MODULE_IMPLEMENTATION_PLAN.md section 15.4) do not exist on main, so I could not update them. I put a short note in the README instead.
  • Rules I followed to the letter: promotion/demotion is floor(size * 20 / 100) each, with no minimum-points guard, so a participant with 0 points can be promoted if the cohort is mostly idle. Equal scores keep the Redis order (reverse lexicographic by user id).
  • Known limits: a user who earns XP in the first seconds of a week before the rollover has created their row gets a row in the division of their last finalized week (the rollover then leaves that row alone). Late joiners are never moved between cohorts mid-week, so a cohort that started under 10 is not merged until the next rollover. The applied-award set is wiped by a Redis flush, so a job that is retried after a flush and after a ledger rebuild could count once more.
  • Only weekKey = Sunday date (UTC), not ISO weeks, because the week starts on Sunday.

Closes #353

…lover

Adds the weekly leagues module (Bronze to Grandmaster):

- LeagueStanding model plus migration 0012-leagues (indexes, and
  leagues.participate=false backfilled on existing user settings)
- cohort partitioning into groups of ~30, a leftover under 10 is merged
  into the previous cohort
- live standings as Redis sorted sets league:{weekKey}:{division}:{cohortId},
  behind a small LeagueScoreStore interface so tests use an in-memory fake
- league-score worker: the XP processor enqueues every awarded (>0 XP)
  ledger write and the worker ZINCRBYs the user's cohort, once per award
- weekly rollover worker (Sunday 00:00 UTC repeatable job): finalizes
  ranks, promotes top 20%, demotes bottom 20%, places everyone in new
  cohorts and sends a league_week_finalized SSE event; idempotent per week key
- GET /api/v1/leagues/current and PUT /api/v1/leagues/participation
- Redis can be rebuilt from the XpTransaction ledger

Closes VarshithReddy2006#353

Signed-off-by: Abhishek <abhishekcse2004@gmail.com>
@VarshithReddy2006 VarshithReddy2006 added enhancement New feature or request help wanted Extra attention is needed level3 10 points - core logic, database changes, and complex features. nsoc26 labels Nov 16, 2026
@VarshithReddy2006

Copy link
Copy Markdown
Owner

All CI checks passed! However, PR #380 was just merged into main, which introduced a small merge conflict in backend/src/shared/events/eventContract.ts (both PRs add a new event type to the contract).

Please merge the latest main into your branch and resolve the conflict in backend/src/shared/events/eventContract.ts so we can merge this PR!

@VarshithReddy2006
VarshithReddy2006 merged commit 7b9bdd9 into VarshithReddy2006:main Nov 16, 2026
@VarshithReddy2006

Copy link
Copy Markdown
Owner

Resolved merge conflict in \�ackend/src/shared/events/eventContract.ts\ against main and squash-merged! Thanks @Anshuu2004.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request help wanted Extra attention is needed level3 10 points - core logic, database changes, and complex features. nsoc26

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(leagues,m9): implement Redis sorted-set weekly leaderboards, cohort assignment, and Sunday 00:00 UTC rollover worker

2 participants